<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * Used for remote version checking.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMUpdateManager {

	const NEWS_RSS_URL = "http://digital.library.unlv.edu/software/dmbridge/feed";
	const HTTP_TIMEOUT = 6;

	/** DMHTTPRequest */
	private $request;

	/**
	 * @param DMHTTPRequest request An HTTP request, which does not need to be
	 * configured at all.
	 */
	public function __construct(DMHTTPRequest $req) {
		$this->request = $req;
	}

	/**
	 * @param int num Get the <num> most recent items
	 * @return array Array of DMNewsItem objects
	 */
	public function getNewsItems($num) {
		$items = array();
		$this->request->setURI(new DMURI(self::NEWS_RSS_URL));
		$client = new DMHTTPClient($this->request);
		$response = $client->send();

		if ($response->getRepresentation()->getBody()) {
			$dxml = new DOMDocument("1.0", "utf-8");
			@$dxml->loadXML($response->getRepresentation()->getBody());
			$dxp = new DOMXPath($dxml);

			$i = 0;
			foreach ($dxp->query("//channel/item") as $item) {
				if ($i >= $num) {
					break;
				}
				$ni = new DMNewsItem();
				$ni->setTitle($item->getElementsByTagName("title")->item(0)->nodeValue);
				$ni->setURL($item->getElementsByTagName("link")->item(0)->nodeValue);
				$ni->setDate(new DMDateTime($item->getElementsByTagName("pubDate")->item(0)->nodeValue));
				$ni->setBody($item->getElementsByTagName("description")->item(0)->nodeValue);
				$items[] = $ni;
				$i++;
			}
		}

		return $items;
	}

}
